package com.ruoyi.wechat.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

public class OrderIdUtils {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private static int sequence = 0;
    private static final int MAX_SEQUENCE = 9999; // 自定义序列号的范围

    public static String genOrderNum(String merchantId) {
        synchronized (OrderIdUtils.class) {
            if (sequence > MAX_SEQUENCE) {
                sequence = 0;
            }
            String timestamp = sdf.format(new Date());
            String sequenceStr = String.format("%04d", sequence++);
            // 拼接商户ID + 时间戳 + 自定义序列号
            String orderNumber = timestamp + sequenceStr;

            // 补足最终订单号长度为32位，可以根据实际情况自定义处理
            if (orderNumber.length() < 21) {
                int remainLength = 21 - orderNumber.length();
                StringBuilder sb = new StringBuilder(orderNumber);
                for (int i = 0; i < remainLength; i++) {
                    sb.append("0");
                }
                orderNumber = sb.toString();
            }

            return orderNumber;
        }
    }

    public static void main(String[] args) {
        String merchantId = "M123456789"; // 商户ID
        String orderNumber = genOrderNum(merchantId);
        System.out.println("生成的订单号为：" + orderNumber);
    }
}